import json
import requests
import time
from urllib import parse
import re
import os
import os.path
import wx
import pawindow


header = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/83.0.4103.97 "
                  "Safari/537.36 Edg/83.0.478.45"
}


def answer(url_):
    r = requests.get(url_, headers=header)
    data = r.text
    jsonobj = json.loads(data)
    return jsonobj


class PAFrame(pawindow.PAzhihu):
    def __init__(self, parent):
        pawindow.PAzhihu.__init__(self, parent)

    def select_file(self, event):
        dlg = wx.DirDialog(self, u"选择文件夹", style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.ospath.SetValue(dlg.GetPath())

    def save_images(self, event):
        text = self.url_input.GetValue()
        text = re.sub("\D", "", text)[0:9]
        url = "https://www.zhihu.com/api/v4/questions/" + text + "/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%2Cis_recognized%2Cpaid_info%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset=0&platform=desktop&sort_by=default"
        # 获取回答总数
        answer_total = int(answer(url)['paging']['totals'])
        offset = 0
        while offset < answer_total:
            url = "https://www.zhihu.com/api/v4/questions/" + text + "/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%2Cis_recognized%2Cpaid_info%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset=" + str(
                offset) + "&platform=desktop&sort_by=default"
            offset += 5
            # print(offset)
            answer_row = answer(url)
            data = answer_row['data']
            if data.__len__ == 0:
                break
            else:
                for index, data_ in enumerate(data):
                    # 回答正文
                    answer_content = data[index]['content']
                    # 使用正则获取图片URL
                    img_urls = re.findall('src=\"(https://.*?)"', answer_content)
                    # 去除重复的URL
                    img_urls = list(set(img_urls))
                    print(json.dumps(img_urls))
                    # 回答中没有图片，跳过
                    if img_urls.__len__() == 0:
                        break
                    for img_url in img_urls:
                        local_path = parse.urlsplit(img_url)[2].replace("/", "")
                        dir_path = self.ospath.GetValue() + "\\"
                        f = open(dir_path + local_path, 'wb')
                        f.write(requests.get(img_url, headers=header).content)
                        f.close()
                        time.sleep(1)
        time.sleep(1)


def main():
    app = wx.App(False)
    frame = PAFrame(None)
    frame.Show(True)
    app.MainLoop()


if __name__ == "__main__":
    main()
    pass